import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export interface User {
  id: string
  email: string
  username: string
  preferences: {
    theme: 'light' | 'dark'
    language: 'zh' | 'en'
    defaultModel: string
  }
}

interface AuthState {
  user: User | null
  token: string | null
  isAuthenticated: boolean
  isLoading: boolean
  login: (email: string, password: string) => Promise<void>
  logout: () => void
  setUser: (user: User) => void
  setToken: (token: string) => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: {
        id: '1',
        email: 'demo@example.com',
        username: 'demo',
        preferences: {
          theme: 'light',
          language: 'zh',
          defaultModel: 'doubao-seed-1-6-250615'
        }
      },
      token: 'demo-token',
      isAuthenticated: true,
      isLoading: false,

      login: async (email: string, password: string) => {
        set({ isLoading: true })
        try {
          // TODO: 实现实际的登录逻辑
          console.log('Logging in with:', email)
          
          // 模拟登录
          const mockUser: User = {
            id: '1',
            email,
            username: email.split('@')[0],
            preferences: {
              theme: 'light',
              language: 'zh',
              defaultModel: 'gpt-3.5-turbo'
            }
          }
          const mockToken = 'mock-jwt-token'
          
          set({ 
            user: mockUser, 
            token: mockToken,
            isAuthenticated: true,
            isLoading: false 
          })
        } catch (error) {
          set({ isLoading: false })
          throw error
        }
      },

      logout: () => {
        set({ 
          user: null, 
          token: null, 
          isAuthenticated: false 
        })
      },

      setUser: (user: User) => {
        set({ user, isAuthenticated: true })
      },

      setToken: (token: string) => {
        set({ token })
      }
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({ 
        user: state.user, 
        token: state.token,
        isAuthenticated: state.isAuthenticated
      })
    }
  )
)